import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import alarmWebSocket from '@/utils/alarmWebSocket'

export const useAlarmSystemStore = defineStore('alarmSystem', () => {
  // 状态数据
  const areas = ref([
    {
      id: 1,
      name: '生产区域A',
      description: '主要生产线区域',
      devices: [
        {
          id: 1,
          name: '工位001',
          deviceId: 'WS001',
          status: 'green',
          isAlarming: false,
          online: true,
          lastAlarmTime: null,
          position: { x: 100, y: 100 },
          type: 'assembly'
        },
        {
          id: 2,
          name: '工位002',
          deviceId: 'WS002',
          status: 'yellow',
          isAlarming: true,
          online: true,
          lastAlarmTime: '2024-01-15 14:30:25',
          position: { x: 300, y: 100 },
          type: 'assembly'
        },
        {
          id: 3,
          name: '工位003',
          deviceId: 'WS003',
          status: 'red',
          isAlarming: true,
          online: true,
          lastAlarmTime: '2024-01-15 14:25:10',
          position: { x: 500, y: 100 },
          type: 'assembly'
        }
      ]
    },
    {
      id: 2,
      name: '生产区域B',
      description: '辅助生产线区域',
      devices: [
        {
          id: 4,
          name: '工位004',
          deviceId: 'WS004',
          status: 'green',
          isAlarming: false,
          online: true,
          lastAlarmTime: null,
          position: { x: 100, y: 300 },
          type: 'testing'
        },
        {
          id: 5,
          name: '工位005',
          deviceId: 'WS005',
          status: 'off',
          isAlarming: false,
          online: false,
          lastAlarmTime: null,
          position: { x: 300, y: 300 },
          type: 'testing'
        }
      ]
    }
  ])

  const alarmHistory = ref([
    {
      id: 1,
      deviceId: 'WS003',
      deviceName: '工位003',
      areaName: '生产区域A',
      alarmType: 'red',
      severity: 'critical',
      startTime: '2024-01-15 14:25:10',
      endTime: null,
      duration: '进行中',
      description: '设备故障报警',
      operator: null,
      acknowledged: false
    },
    {
      id: 2,
      deviceId: 'WS002',
      deviceName: '工位002',
      areaName: '生产区域A',
      alarmType: 'yellow',
      severity: 'warning',
      startTime: '2024-01-15 14:30:25',
      endTime: null,
      duration: '进行中',
      description: '设备维护提醒',
      operator: null,
      acknowledged: false
    },
    {
      id: 3,
      deviceId: 'WS001',
      deviceName: '工位001',
      areaName: '生产区域A',
      alarmType: 'yellow',
      severity: 'warning',
      startTime: '2024-01-15 13:15:30',
      endTime: '2024-01-15 13:45:20',
      duration: '29分50秒',
      description: '设备维护提醒',
      operator: '张三',
      acknowledged: true
    }
  ])

  const systemSettings = ref({
    autoRefreshInterval: 5000, // 自动刷新间隔（毫秒）
    soundEnabled: true, // 声音报警
    notificationEnabled: true, // 通知提醒
    maxHistoryRecords: 1000, // 最大历史记录数
    alarmLevels: {
      red: { name: '故障报警', color: '#f56c6c', priority: 1 },
      yellow: { name: '维护提醒', color: '#e6a23c', priority: 2 },
      green: { name: '正常运行', color: '#67c23a', priority: 3 },
      off: { name: '离线', color: '#909399', priority: 4 }
    }
  })

  const connectionStatus = ref({
    isConnected: false,
    lastConnectTime: null,
    reconnectAttempts: 0
  })

  // 计算属性
  const totalDevices = computed(() => {
    return areas.value.reduce((total, area) => total + area.devices.length, 0)
  })

  const onlineDevices = computed(() => {
    return areas.value.reduce((total, area) => {
      return total + area.devices.filter(device => device.online).length
    }, 0)
  })

  const alarmingDevices = computed(() => {
    return areas.value.reduce((total, area) => {
      return total + area.devices.filter(device => device.isAlarming).length
    }, 0)
  })

  const criticalAlarms = computed(() => {
    return alarmHistory.value.filter(alarm => 
      alarm.severity === 'critical' && !alarm.acknowledged
    ).length
  })

  const warningAlarms = computed(() => {
    return alarmHistory.value.filter(alarm => 
      alarm.severity === 'warning' && !alarm.acknowledged
    ).length
  })

  const devicesByStatus = computed(() => {
    const statusCount = { red: 0, yellow: 0, green: 0, off: 0 }
    areas.value.forEach(area => {
      area.devices.forEach(device => {
        statusCount[device.status] = (statusCount[device.status] || 0) + 1
      })
    })
    return statusCount
  })

  // 方法
  const findDeviceById = (deviceId) => {
    for (const area of areas.value) {
      const device = area.devices.find(d => d.deviceId === deviceId)
      if (device) {
        return { device, area }
      }
    }
    return null
  }

  const findDeviceByInternalId = (id) => {
    for (const area of areas.value) {
      const device = area.devices.find(d => d.id === id)
      if (device) {
        return { device, area }
      }
    }
    return null
  }

  const updateDeviceStatus = (deviceId, status, isAlarming = false, timestamp = null) => {
    const result = findDeviceById(deviceId)
    if (result) {
      const { device } = result
      device.status = status
      device.isAlarming = isAlarming
      device.online = true
      
      if (timestamp) {
        device.lastAlarmTime = timestamp
      }
      
      // 如果是报警状态，添加到历史记录
      if (isAlarming && status !== 'green') {
        addAlarmRecord(device, result.area, status, timestamp)
      }
      
      return true
    }
    return false
  }

  const addAlarmRecord = (device, area, alarmType, timestamp = null) => {
    const now = timestamp || new Date().toISOString()
    const severity = alarmType === 'red' ? 'critical' : 'warning'
    
    const alarmRecord = {
      id: Date.now(),
      deviceId: device.deviceId,
      deviceName: device.name,
      areaName: area.name,
      alarmType,
      severity,
      startTime: now,
      endTime: null,
      duration: '进行中',
      description: systemSettings.value.alarmLevels[alarmType]?.name || '未知报警',
      operator: null,
      acknowledged: false
    }
    
    alarmHistory.value.unshift(alarmRecord)
    
    // 限制历史记录数量
    if (alarmHistory.value.length > systemSettings.value.maxHistoryRecords) {
      alarmHistory.value = alarmHistory.value.slice(0, systemSettings.value.maxHistoryRecords)
    }
  }

  const acknowledgeAlarm = (alarmId, operator) => {
    const alarm = alarmHistory.value.find(a => a.id === alarmId)
    if (alarm) {
      alarm.acknowledged = true
      alarm.operator = operator
      alarm.endTime = new Date().toISOString()
      
      // 计算持续时间
      const start = new Date(alarm.startTime)
      const end = new Date(alarm.endTime)
      const duration = Math.floor((end - start) / 1000)
      const minutes = Math.floor(duration / 60)
      const seconds = duration % 60
      alarm.duration = `${minutes}分${seconds}秒`
      
      // 更新设备状态
      const result = findDeviceById(alarm.deviceId)
      if (result) {
        result.device.isAlarming = false
        if (result.device.status !== 'off') {
          result.device.status = 'green'
        }
      }
      
      return true
    }
    return false
  }

  const addDevice = (areaId, deviceData) => {
    const area = areas.value.find(a => a.id === areaId)
    if (area) {
      const newDevice = {
        id: Date.now(),
        name: deviceData.name,
        deviceId: deviceData.deviceId,
        status: 'off',
        isAlarming: false,
        online: false,
        lastAlarmTime: null,
        position: deviceData.position || { x: 0, y: 0 },
        type: deviceData.type || 'assembly'
      }
      area.devices.push(newDevice)
      return newDevice
    }
    return null
  }

  const removeDevice = (deviceId) => {
    for (const area of areas.value) {
      const index = area.devices.findIndex(d => d.id === deviceId)
      if (index > -1) {
        area.devices.splice(index, 1)
        return true
      }
    }
    return false
  }

  const clearAlarmHistory = () => {
    alarmHistory.value = []
  }

  const updateConnectionStatus = (status) => {
    connectionStatus.value = {
      ...connectionStatus.value,
      ...status
    }
  }

  const getAreaStatistics = (areaId) => {
    const area = areas.value.find(a => a.id === areaId)
    if (!area) return null
    
    const stats = {
      total: area.devices.length,
      online: 0,
      alarming: 0,
      statusCount: { red: 0, yellow: 0, green: 0, off: 0 }
    }
    
    area.devices.forEach(device => {
      if (device.online) stats.online++
      if (device.isAlarming) stats.alarming++
      stats.statusCount[device.status] = (stats.statusCount[device.status] || 0) + 1
    })
    
    return stats
  }

  const exportAlarmHistory = (startDate = null, endDate = null) => {
    let filteredHistory = alarmHistory.value
    
    if (startDate || endDate) {
      filteredHistory = alarmHistory.value.filter(alarm => {
        const alarmDate = new Date(alarm.startTime)
        if (startDate && alarmDate < new Date(startDate)) return false
        if (endDate && alarmDate > new Date(endDate)) return false
        return true
      })
    }
    
    return filteredHistory.map(alarm => ({
      设备名称: alarm.deviceName,
      所属区域: alarm.areaName,
      报警类型: systemSettings.value.alarmLevels[alarm.alarmType]?.name,
      严重程度: alarm.severity,
      开始时间: alarm.startTime,
      结束时间: alarm.endTime || '进行中',
      持续时间: alarm.duration,
      描述: alarm.description,
      处理人员: alarm.operator || '未处理',
      是否确认: alarm.acknowledged ? '是' : '否'
    }))
  }

  // WebSocket 消息处理
  const setupWebSocketHandlers = () => {
    // 设备报警消息处理
    alarmWebSocket.onMessage('device_alarm', (message) => {
      const { deviceId, alarmType, severity, timestamp, description } = message
      updateDeviceStatus(deviceId, alarmType, true, timestamp)
    })

    // 设备状态更新消息处理
    alarmWebSocket.onMessage('device_status_update', (message) => {
      const { deviceId, status, online, timestamp } = message
      const result = findDeviceById(deviceId)
      if (result) {
        result.device.status = status
        result.device.online = online
        if (timestamp) {
          result.device.lastAlarmTime = timestamp
        }
      }
    })

    // 连接状态更新
    alarmWebSocket.onMessage('connection_status', (message) => {
      updateConnectionStatus(message)
    })
  }

  // 初始化
  const initialize = () => {
    setupWebSocketHandlers()
    // 可以在这里加载持久化数据
  }

  return {
    // 状态
    areas,
    alarmHistory,
    systemSettings,
    connectionStatus,
    
    // 计算属性
    totalDevices,
    onlineDevices,
    alarmingDevices,
    criticalAlarms,
    warningAlarms,
    devicesByStatus,
    
    // 方法
    findDeviceById,
    findDeviceByInternalId,
    updateDeviceStatus,
    addAlarmRecord,
    acknowledgeAlarm,
    addDevice,
    removeDevice,
    clearAlarmHistory,
    updateConnectionStatus,
    getAreaStatistics,
    exportAlarmHistory,
    setupWebSocketHandlers,
    initialize
  }
})